/*
 * Copyright (C) 2011 JiangHongTiao
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package sk.lieskove.jianghongtiao.paris.core;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import sk.lieskove.jianghongtiao.commonpersist.Persist;
import sk.lieskove.jianghongtiao.websearch.persistence.ClassificationStorage;
import sk.lieskove.jianghongtiao.websearch.enums.DocumentType;
import sk.lieskove.jianghongtiao.paris.core.search.PeopleNameListSearch;
import sk.lieskove.jianghongtiao.paris.core.search.ThreadPeopleSearch;
import sk.lieskove.jianghongtiao.websearch.persistence.WebSearchResponse;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

/**
 *
 * Search for people on the Internet. List of people is specified in
 * the plain text file. Every line of this text file represents one person. 
 * Program will search on Internet for every person in this file. Results 
 * are stored in the database. 
 * @author xjuraj
 */
public class PlainFilePeopleSearch {

    private static final transient Logger log = Logger.getLogger(PlainFilePeopleSearch.class);

    public static void usage() {
        System.out.println("Program requires one parameter: path to plain text file"
                + " with list of persons. Each person's name have to be placed on "
                + "the single line. ");
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        if ((args != null) && (args.length == 1)) {
            if (args[0].equals("-h") || args[0].equals("--help")
                    || (args[0].equals("-help"))) {
                usage();
                return;
            } else {
                File f = new File(args[0]);
                if ((f.exists())) {
                    loadAndSearch(f);
                } else {
                    System.err.println("File: '" + f.getAbsolutePath()
                            + "' was not found!");
                    usage();
                    return;
                }
            }
        } else {
            usage();
            return;
        }
    }

    private static void loadAndSearch(File file) {
        if ((file == null) || (!file.exists())) {
            throw new IllegalArgumentException("Wrong file: " + file);
        }

        Long start = System.currentTimeMillis();
        try {
            List<String> peopleList = FileUtils.readLines(file);
            PeopleNameListSearch tps = new ThreadPeopleSearch();
            List<WebSearchResponse> results = tps.searchForPeople(peopleList);
            persistResults(results);
            printResults(results);
        } catch (IOException ex) {
            log.error("IO Exception with file: " + file.getAbsolutePath());
        }
        Timestamp time = new Timestamp(System.currentTimeMillis() - start);
        System.out.println("Running time: " + time.toString());
    }

    private static void printResults(List<WebSearchResponse> searchAll) {
        Persist p = Persist.getSingleton();
        for (int i = 0; i < searchAll.size(); i++) {
            WebSearchResponse resp = searchAll.get(i);
            if (resp.getFile() != null) {
                System.out.println(resp.getServiceName() + "[" + resp.getSearchPosition()
                        + "]: " + resp.getTitle() + "\t\t\t\t\t File: " + resp.getFile().getAbsolutePath());
            } else {
                System.out.println(resp.getServiceName() + "[" + resp.getSearchPosition()
                        + "]: " + resp.getTitle() + "\t\t\t\t\t File: is NULL");
            }
        }
    }

    private static void persistResults(List<WebSearchResponse> searchAll) {
        Persist p = Persist.getSingleton();
        for (int i = 0; i < searchAll.size(); i++) {
            WebSearchResponse resp = searchAll.get(i);
            ClassificationStorage cs = new ClassificationStorage();
            cs.setDocumentType(DocumentType.UNKNOWN);
            cs.setWebSearchResponse(resp);
            System.out.println("Store: " + resp.getUrl());
            p.remoteObjects(cs);
        }
    }
}
